package com.jservice.framework.authc;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by cwledit on 17/5/26.
 */
public class AuthcUtil {

    public static final Logger logger = Logger.getLogger(AuthcUtil.class);

    /**
     * 缓存权限配置对象
     */
    private static Map<String,AuthcConfig> AUTHC_MAPPING = new HashMap<>();

    private static List<AuthcConfig> AUTHC_LIST = new ArrayList<>();

    /**
     * 系统注册的urls
     */
    private static Set<String> ALL_URLS = new HashSet<>();

    public static void initAuthcConfig(String fileName) throws IOException, JDOMException {
        File file = ResourceUtils.getFile("classpath:"+fileName);
        SAXBuilder xmlBuilder = new SAXBuilder();
        Document doc = xmlBuilder.build(file);
        Element objRoot = doc.getRootElement();
        AuthcConfig authcConfig = null;
        List<Element> authcList = objRoot.getChildren("authc");
        for (Element authc : authcList){
            String key = authc.getAttribute("key").getValue();
            String name = authc.getAttributeValue("name");
            String isMenu = authc.getAttributeValue("isMenu");
            String module = authc.getAttributeValue("module");
            boolean isMenuBoolean = false;
            if("true".equalsIgnoreCase(isMenu)){
                isMenuBoolean = true;
            }
            Set<String> urls = new HashSet<>();
            List<Element> urlList= authc.getChildren("url");
            for (Element url : urlList){
                String urlText = url.getTextTrim();
                urls.add(urlText);
            }
            authcConfig = new AuthcConfig();
            authcConfig.setKey(key);
            authcConfig.setMenu(isMenuBoolean);
            authcConfig.setModule(module);
            authcConfig.setName(name);
            authcConfig.setUrls(urls);
            AUTHC_MAPPING.put(key,authcConfig);
            AUTHC_LIST.add(authcConfig);
            logger.debug("AUTHC MAPPING: KEY["+key+"] URLS["+ StringUtils.collectionToCommaDelimitedString(urls));
        }
        logger.info("AUTHC HAS BEEN STARTED");

    }

    /**
     * 获得
     * @return
     */
    public static List<AuthcConfig> getAllAuthcConfigs(){
        return AUTHC_LIST;
    }

    public static AuthcConfig getAuthcConfig(String key){
        return AUTHC_MAPPING.get(key);
    }





    public static void main(String[] args) throws IOException, JDOMException {
        String fileName = "authc.xml";
        AuthcUtil.initAuthcConfig(fileName);
        AuthcConfig authcConfig = AuthcUtil.getAuthcConfig("user:manager");
        System.out.println(authcConfig.getUrls());
    }




}
